<template>
  <AutoComplete v-bind="bindProps" @change="onChange" @search="onSearch">
    <!-- <template #option="item">
      <div style="display: flex; justify-content: space-between" @mousedown="e => e.preventDefault()">
        <span>{{ item.label }}</span>
        <div style="position: absolute; right: 5%;" :class="[ `${prefixCls}-delete` ]">
          <Icon icon="i-ant-design:delete-outlined" ></Icon>
        </div>
      </div>
    </template> -->
  </AutoComplete>
</template>

<script lang="ts">
  import { propTypes } from "/@/utils/propTypes"
  import { defineComponent, ref, watch, computed } from "vue"
  import { AutoComplete } from "ant-design-vue"
  import { Icon } from "/@/components/Icon"
  import { useDesign } from "/@/hooks/web/useDesign"

  export default defineComponent({
    name: "MyAutoComplete",
    props: {
      options: propTypes.array.def(() => []),
      optionFilterProp: propTypes.string.def("label"),
    },
    components: { AutoComplete, Icon },
    emits: ["change", "update:value"],
    setup(props, { emit, attrs }) {
      // 内部 options 选项
      const options = ref<any[]>([])
      const useOptions = ref<any[]>([])
      const { prefixCls } = useDesign("my-auto-complete")

      // 监听外部 options 变化，并覆盖内部 options
      watch(
        () => props.options,
        () => {
          options.value = [...props.options]
          useOptions.value = [...props.options]
        },
        { deep: true, immediate: true }
      )
      // 合并 props 和 attrs
      const bindProps: any = computed(() =>
        Object.assign(
          { ...props },
          { ...attrs },
          {
            options: useOptions.value,
          }
        )
      )

      function onChange(value) {
        emit("change", value)
        emit("update:value", value)
      }

      function onSearch(value) {
        useOptions.value = options.value.filter((e) => e?.[props.optionFilterProp].includes(value))
      }

      return {
        prefixCls,
        bindProps,
        onChange,
        onSearch,
      }
    },
  })
</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-my-auto-complete";
  .@{prefix-cls}-delete {
    color: #ff4d4f;
    padding: 1px;
  }

  .@{prefix-cls}-delete:hover {
    background-color: @menu-active-bg;
    border-radius: 2px;
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
  }
</style>
